<?php

namespace app\user\controller;

use cmf\controller\RestBaseController;
use think\Db;
use think\Validate;

class UserController extends RestBaseController
{
    
    // 用户注册
    public function register()
    {
        $validate = new Validate([
            'username'          => 'require',
            'password'          => 'require',
            //            'verification_code' => 'require'
        ]);
        $validate->message([
            'username.require'          => '请输入手机号, 邮箱!',
            'password.require'          => '请输入您的密码!',
            //            'verification_code.require' => '请输入数字验证码!'
        ]);
        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        $user          = [];
        $findUserWhere = [];
        if (Validate::is($data['username'], 'email')) {
            $user['user_email']          = $data['username'];
            $findUserWhere['user_email'] = $data['username'];
        } else if (preg_match('/(^(13\d|15[^4\D]|17[013678]|18\d)\d{8})$/', $data['username'])) {
            $user['mobile']          = $data['username'];
            $findUserWhere['mobile'] = $data['username'];
        } else {
            $this->error(" 请输入正确的手机或者邮箱格式!");
        }
        $errMsg = cmf_check_verification_code($data['username'], $data['verification_code']);
        if (!empty($errMsg)) {
            $this->error($errMsg);
        }
        $findUserCount = Db::name("user")->where($findUserWhere)->count();
        if ($findUserCount > 0) {
            $this->error(" 此账号已存在!");
        }
        $user['create_time'] = time();
        $user['user_status'] = 1;
        $user['user_type']   = 2;
        $user['user_pass']   = cmf_password($data['password']);
        $result              = Db::name("user")->insert($user);
        if (empty($result)) {
            $this->error(" 注册失败, 请重试!");
        }
        $this->success(" 注册并激活成功, 请登录!");
        
    }
    
    // 用户登录
    public function login()
    {
        $validate = new Validate([
            'username' => 'require',
            'password' => 'require'
        ]);
        $validate->message([
            'username.require' => '请输入手机号, 邮箱或用户名!',
            'password.require' => '请输入您的密码!'
        ]);
        $data = $this->request->param();
        print_r($data);
  
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        $userQuery = Db::name("user");
        if (Validate::is($data['username'], 'email')) {
            $userQuery = $userQuery->where('user_email', $data['username']);
        } else if (preg_match('/(^(13\d|15[^4\D]|17[013678]|18\d)\d{8})$/', $data['username'])) {
            $userQuery = $userQuery->where('mobile', $data['username']);
        } else {
            $userQuery = $userQuery->where('user_login', $data['username']);
        }
        $findUser = $userQuery->find();
        if (empty($findUser)) {
            $this->error(" 用户不存在!");
        } else {
            switch ($findUser['user_status']) {
                case 0:
                    $this->error('您已被拉黑!');
                case 2:
                    $this->error('账户还没有验证成功!');
            }
            if (!cmf_compare_password($data['password'], $findUser['user_pass'])) {
                $this->error(" 密码不正确!");
            }
        }
        $allowedDeviceTypes = ['mobile', 'android', 'iphone', 'ipad', 'web', 'pc', 'mac'];
        if (empty($data['device_type']) || !in_array($data['device_type'], $allowedDeviceTypes)) {
            $this->error(" 请求错误, 未知设备!");
        }
        $userTokenQuery = Db::name("user_token")
            ->where('user_id', $findUser['id'])
            ->where('device_type', $data['device_type']);
        $findUserToken  = $userTokenQuery->find();
        $currentTime    = time();
        $expireTime     = $currentTime + 24 * 3600 * 180;
        $token          = md5(uniqid()) . md5(uniqid());
        if (empty($findUserToken)) {
            $result = $userTokenQuery->insert([
                'token'       => $token,
                'user_id'     => $findUser['id'],
                'expire_time' => $expireTime,
                'create_time' => $currentTime,
                'device_type' => $data['device_type']
            ]);
        } else {
            $result = $userTokenQuery
                ->where('user_id', $findUser['id'])
                ->where('device_type', $data['device_type'])
                ->update([
                    'token'       => $token,
                    'expire_time' => $expireTime,
                    'create_time' => $currentTime
                ]);
        }
        if (empty($result)) {
            $this->error(" 登录失败!");
        }
        $this->success('登录成功', ['token' => $token, 'user' => $findUser]);
    }
    
    // 管理员退出
    public function logout()
    {
        $userId = $this->getUserId();
        Db::name('user_token')->where([
            'token'       => $this->token,
            'user_id'     => $userId,
            'device_type' => $this->deviceType
        ])->update(['token' => '']);
        $this->success(" 退出成功!");
    }
    
    public function upload_head_img()
    {
        /*********** 接收参数  ***********/
        $data = $this->params;
        
        /*********** 上传文件,获得路径  ***********/
        $head_img_path = $this->upload_file($data['user_icon'], 'head_img');
        /*********** 存入数据库  ***********/
        $res = db('user')->where('user_id', $data['user_id'])->setField('user_icon', $head_img_path);
        if ($res) {
            $this->return_msg(200, '头像上传成功!', $head_img_path);
        } else {
            $this->return_msg(400, '上传头像失败!');
        }
    }
    
    public function change_pwd()
    {
        /*********** 接收参数  ***********/
        $data = $this->params;
        /*********** 检查用户名并取出数据库中的密码  ***********/
        $user_name_type = $this->check_username($data['user_name']);
        switch ($user_name_type) {
            case 'phone':
                $this->check_exist($data['user_name'], 'phone', 1);
                $where['user_phone'] = $data['user_name'];
                break;
            case 'email':
                $this->check_exist($data['user_name'], 'email', 1);
                $where['user_email'] = $data['user_name'];
                break;
        }
        /*********** 判断原始密码是否正确  ***********/
        $db_ini_pwd = db('user')->where($where)->value('user_pwd');
        if ($db_ini_pwd !== $data['user_ini_pwd']) {
            $this->return_msg(400, '原密码错误!');
        }
        /*********** 把新的密码存入数据库  ***********/
        $res = db('user')->where($where)->setField('user_pwd', $data['user_pwd']);
        if ($res !== false) {
            $this->return_msg(200, '密码修改成功!');
        } else {
            $this->return_msg(400, '密码修改失败!');
        }
    }
    
    public function find_pwd()
    {
        /*********** 接收参数  ***********/
        $data = $this->params;
        /*********** 检测验证码  ***********/
        $this->check_code($data['user_name'], $data['code']);
        /*********** 检测用户名  ***********/
        $user_name_type = $this->check_username($data['user_name']);
        switch ($user_name_type) {
            case 'phone':
                $this->check_exist($data['user_name'], 'phone', 1);
                $where['user_phone'] = $data['user_name'];
                break;
            case 'email':
                $this->check_exist($data['user_name'], 'email', 1);
                $where['user_email'] = $data['user_name'];
                break;
        }
        /*********** 修改数据库  ***********/
        $res = db('user')->where($where)->setField('user_pwd', $data['user_pwd']);
        if ($res !== false) {
            $this->return_msg(200, '密码修改成功!');
        } else {
            $this->return_msg(400, '密码修改失败!');
        }
    }
    
    public function bind_phone()
    {
        /*********** 接收参数  ***********/
        $data = $this->params;
        /*********** 检查验证码  ***********/
        $this->check_code($data['phone'], $data['code']);
        /*********** 修改数据库  ***********/
        $res = db('user')->where('user_id', $data['user_id'])->setField('user_phone', $data['phone']);
        if ($res !== false) {
            $this->return_msg(200, '手机号绑定成功!');
        } else {
            $this->return_msg(400, '手机号绑定失败!');
        }
    }
    
    public function bind_email()
    {
        /*********** 接收参数  ***********/
        $data = $this->params;
        /*********** 检查验证码  ***********/
        $this->check_code($data['email'], $data['code']);
        /*********** 修改数据库  ***********/
        $res = db('user')->where('user_id', $data['user_id'])->setField('user_email', $data['email']);
        if ($res !== false) {
            $this->return_msg(200, '邮箱绑定成功!');
        } else {
            $this->return_msg(400, '邮箱绑定失败!');
        }
    }
    
    public function bind_username()
    {
        /*********** 接收参数  ***********/
        $data = $this->params;
        /*********** 检测验证码  ***********/
        $this->check_code($data['user_name'], $data['code']);
        /*********** 判断用户名  ***********/
        $user_name_type = $this->check_username($data['user_name']);
        switch ($user_name_type) {
            case 'phone':
                $type_text                 = '手机号';
                $update_data['user_phone'] = $data['user_name'];
                break;
            case 'email':
                $type_text                 = '邮箱';
                $update_data['user_email'] = $data['user_name'];
                break;
        }
        /*********** 修改数据库  ***********/
        $res = db('user')->where('user_id', $data['user_id'])->update($update_data);
        if ($res !== false) {
            $this->return_msg(200, $type_text . '绑定成功!');
        } else {
            $this->return_msg(400, $type_text . '绑定失败!');
        }
    }
    
    public function set_nickname()
    {
        /*********** 接收参数  ***********/
        $data = $this->params;
        /*********** 检测昵称  ***********/
        $res = db('user')->where('user_nickname', $data['user_nickname'])->find();
        if ($res) {
            $this->return_msg(400, '该昵称已被占用!');
        }
        /*********** 写入数据库  ***********/
        $res = db('user')->where('user_id', $data['user_id'])->setField('user_nickname', $data['user_nickname']);
        if (!$res) {
            $this->return_msg(400, '修改昵称失败!');
        } else {
            $this->return_msg(200, '昵称修改成功!');
        }
    }
}
